package com.android.wake_up_enable_hotspot;

import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.android.wake_up_enable_hotspot.databinding.ActivityBtDeviceListBinding;
import com.android.wake_up_enable_hotspot.databinding.ListItemDeviceBinding;
import com.socks.klog.BuildConfig;
import com.socks.library.KLog;

import java.util.ArrayList;
import java.util.List;

public class BtDeviceListActivity extends AppCompatActivity {

    private ActivityBtDeviceListBinding binding;
    private BluetoothAdapter bluetoothAdapter;
    ProgressDialog dialog;
    private ItemAdapter itemAdapter;
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            char c;
            String intentAction = intent.getAction();
            switch (intentAction.hashCode()) {
                case -1780914469:
                    if (intentAction.equals("android.bluetooth.adapter.action.DISCOVERY_FINISHED")) {
                        c = 3;
                        break;
                    }
                    c = 65535;
                    break;
                case -301431627:
                    if (intentAction.equals("android.bluetooth.device.action.ACL_CONNECTED")) {
                        c = 0;
                        break;
                    }
                    c = 65535;
                    break;
                case 6759640:
                    if (intentAction.equals("android.bluetooth.adapter.action.DISCOVERY_STARTED")) {
                        c = 2;
                        break;
                    }
                    c = 65535;
                    break;
                case 1167529923:
                    if (intentAction.equals("android.bluetooth.device.action.FOUND")) {
                        c = 4;
                        break;
                    }
                    c = 65535;
                    break;
                case 1821585647:
                    if (intentAction.equals("android.bluetooth.device.action.ACL_DISCONNECTED")) {
                        c = 1;
                        break;
                    }
                    c = 65535;
                    break;
                default:
                    c = 65535;
                    break;
            }
            switch (c) {
                case 0:
                    BluetoothDevice bluetoothDevice = (BluetoothDevice) intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
                    KLog.e();
                    return;
                case 1:
                    BluetoothDevice bluetoothDevice2 = (BluetoothDevice) intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
                    KLog.e();
                    return;
                case 2:
                    KLog.e("蓝牙搜索开始");
                    BtDeviceListActivity.this.dialog.show();
                    return;
                case 3:
                    KLog.e("蓝牙搜索结束");
                    BtDeviceListActivity.this.dialog.dismiss();
                    BtDeviceListActivity.this.binding.scanBtn.setText("开始扫描");
                    if (BtDeviceListActivity.this.itemAdapter.getDataList().isEmpty()) {
                        new AlertDialog.Builder(BtDeviceListActivity.this)
                                .setTitle("提示")
                                .setMessage("未搜索到蓝牙设备，请稍候重试。")
                                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                    }
                                }).show();
                        return;
                    }
                    return;
                case 4:
                    short rssi = intent.getShortExtra("android.bluetooth.device.extra.RSSI", (short) 0);
                    BluetoothDevice scanDevice = (BluetoothDevice) intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
                    if (scanDevice == null) {
                        return;
                    }
                    if (ActivityCompat.checkSelfPermission(BtDeviceListActivity.this, "android.permission.BLUETOOTH_CONNECT") != 0 && Build.VERSION.SDK_INT >= 31) {
                        ActivityCompat.requestPermissions(BtDeviceListActivity.this, new String[]{"android.permission.BLUETOOTH_CONNECT"}, 0);
                        return;
                    }
                    String s = scanDevice.toString();
                    KLog.e(scanDevice.getName() + " " + scanDevice.getAddress() + " " + ((int) rssi) + " " + s);
                    ItemDataBean bean = new ItemDataBean();
                    bean.device = scanDevice;
                    bean.rssi = rssi;
                    if (scanDevice.getName() != null) {
                        BtDeviceListActivity.this.itemAdapter.addItem(bean);
                        return;
                    }
                    return;
                default:
                    return;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityBtDeviceListBinding inflate = ActivityBtDeviceListBinding.inflate(getLayoutInflater());
        this.binding = inflate;
        setContentView(inflate.getRoot());
        this.itemAdapter = new ItemAdapter();
        this.binding.recyclerView.setAdapter(this.itemAdapter);
        this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        ProgressDialog progressDialog = new ProgressDialog(this);
        this.dialog = progressDialog;
        progressDialog.setMessage("蓝牙设备搜索中。。。");
        this.dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
//                BtDeviceListActivity btDeviceListActivity = BtDeviceListActivity.this;
//                btDeviceListActivity.startScan(btDeviceListActivity.binding.scanBtn);
                bluetoothAdapter.cancelDiscovery();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.bluetooth.device.action.FOUND");
        filter.addAction("android.bluetooth.adapter.action.DISCOVERY_STARTED");
        filter.addAction("android.bluetooth.adapter.action.DISCOVERY_FINISHED");
        filter.addAction("android.bluetooth.device.action.ACL_CONNECTED");
        filter.addAction("android.bluetooth.device.action.ACL_DISCONNECTED");
        registerReceiver(this.receiver, filter);
    }

    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver(this.receiver);
    }

    public void startScan(View view) {
        if (ActivityCompat.checkSelfPermission(this, "android.permission.BLUETOOTH_SCAN") != 0 && Build.VERSION.SDK_INT >= 31) {
            ActivityCompat.requestPermissions(this, new String[]{"android.permission.BLUETOOTH_SCAN"}, 0);
        } else if (this.bluetoothAdapter.isDiscovering()) {
            this.bluetoothAdapter.cancelDiscovery();
            this.binding.scanBtn.setText("开始扫描");
        } else {
            this.bluetoothAdapter.startDiscovery();
            this.itemAdapter.reset();
            this.binding.scanBtn.setText("停止扫描");
        }
    }

    public static class ItemDataBean {
        BluetoothDevice device;
        short rssi;

        private ItemDataBean() {
        }
    }

    public static class ItemViewHolder extends RecyclerView.ViewHolder {
        ListItemDeviceBinding deviceBinding;

        public ItemViewHolder(ListItemDeviceBinding deviceBinding) {
            super(deviceBinding.getRoot());
            this.deviceBinding = deviceBinding;
        }
    }

    public class ItemAdapter extends RecyclerView.Adapter<ItemViewHolder> {
        List<ItemDataBean> dataList = new ArrayList();

        public ItemAdapter() {
        }

        @Override
        public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            ListItemDeviceBinding deviceBinding = ListItemDeviceBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
            return new ItemViewHolder(deviceBinding);
        }

        @Override
        public void onBindViewHolder(ItemViewHolder holder, int position) {
            ItemDataBean itemDataBean = this.dataList.get(position);
            final BluetoothDevice bluetoothDevice = itemDataBean.device;
            short rssi = itemDataBean.rssi;
            if (ActivityCompat.checkSelfPermission(holder.deviceBinding.getRoot().getContext(), "android.permission.BLUETOOTH_CONNECT") != 0 && Build.VERSION.SDK_INT >= 31) {
                ActivityCompat.requestPermissions(BtDeviceListActivity.this, new String[]{"android.permission.BLUETOOTH_CONNECT"}, 0);
                return;
            }
            String deviceName = bluetoothDevice.getName();
            String deviceMac = bluetoothDevice.getAddress();
            holder.deviceBinding.name.setText(deviceName);
            holder.deviceBinding.address.setText(deviceMac);
            holder.deviceBinding.rssi.setText(((int) rssi) + BuildConfig.FLAVOR);
            holder.deviceBinding.set.setOnClickListener(new View.OnClickListener() { // from class: com.baidu.unlock_open_hotspot.BtDeviceListActivity.ItemAdapter.1
                @Override // android.view.View.OnClickListener
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.putExtra("android.bluetooth.device.extra.DEVICE", bluetoothDevice);
                    BtDeviceListActivity.this.setResult(-1, intent);
                    BtDeviceListActivity.this.finish();
                }
            });
        }

        @Override
        public int getItemCount() {
            return this.dataList.size();
        }

        public void addItem(ItemDataBean device) {
            notifyItemInserted(this.dataList.size());
            this.dataList.add(device);
        }

        public void reset() {
            notifyItemRangeRemoved(0, this.dataList.size());
            this.dataList.clear();
        }

        public List<ItemDataBean> getDataList() {
            return this.dataList;
        }
    }

}